#!/usr/bin/env python
# coding=utf-8
# __author__ = 'Yunchao Ling'


import importlib, sys

default_encoding = 'utf-8'
if sys.getdefaultencoding() != default_encoding:
    importlib.reload(sys)
    sys.setdefaultencoding(default_encoding)


def test_schema(file_path: str):
    ht = {}
    infile = open(file_path, "r", encoding='utf-8')
    infile.readline()

    for line in infile:
        line = line.rstrip("\n")
        splitline = line.split("\t")

        triple = "%s|%s|%s" % (splitline[2], splitline[0], splitline[3])
        if triple in ht:
            ht[triple] += 1
        else:
            ht[triple] = 1

    infile.close()

    for key in ht:
        if ht[key] > 1:
            print(key)


def load_schema(file_path: str):
    ht = {}
    infile = open(file_path, "r", encoding='utf-8')
    infile.readline()

    for line in infile:
        line = line.rstrip("\n")
        splitline = line.split("\t")

        triple = "%s|%s|%s" % (splitline[2], splitline[0], splitline[3])

        ht[triple] = splitline[6]

    infile.close()

    return ht


def verify_data(file_path: str, schema: dict):
    infile = open(file_path, "r", encoding='utf-8')
    infile.readline()
    count = 1
    for line in infile:
        count += 1
        line = line.rstrip("\n")
        splitline = line.split("\t")
        if splitline[7] != "" and splitline[16] != "":
            triple = "%s|%s|%s" % (splitline[7], splitline[14], splitline[16])
            if triple not in schema:
                print("%d\t%s" % (count, triple))

    infile.close()


def modify_pattern(file_path: str, schema: dict):
    outfile = open(file_path + ".mod", "w", encoding='utf-8')
    infile = open(file_path, "r", encoding='utf-8')
    outfile.write(infile.readline())
    outfile.flush()
    count = 1
    for line in infile:
        count += 1
        line = line.rstrip("\n")
        splitline = line.split("\t")
        if splitline[7] != "" and splitline[16] != "":
            triple = "%s|%s|%s" % (splitline[7], splitline[14], splitline[16])
            pattern = schema[triple]
            for i in range(5):
                outfile.write(splitline[i] + "\t")
            outfile.write(pattern)
            for i in range(6, len(splitline)):
                outfile.write("\t" + splitline[i])
            outfile.write("\n")
            outfile.flush()

    infile.close()
    outfile.close()


if __name__ == '__main__':
    # test_schema("D:/Seafile/Work/生物岛知识图谱/Schema/schema_20230711_3.tsv")
    schema = load_schema("D:/Seafile/Work/生物岛知识图谱/Schema/schema_20230711_3.tsv")
    # verify_data("D:/Seafile/Work/生物岛知识图谱/标注数据/肺癌/LungCancer_0628_2.tsv", schema)
    modify_pattern("D:/Seafile/Work/生物岛知识图谱/标注数据/肺癌/LungCancer_0628_2.tsv", schema)
